package com.unipay.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unipay.common.handler.UnipayException;
import com.unipay.common.helper.HttpRequestHelper;
import com.unipay.common.result.ResultCodeEnum;
import com.unipay.common.utils.MD5;
import com.unipay.enums.OrderStatusEnum;
import com.unipay.enums.PaymentStatusEnum;
import com.unipay.enums.PaymentTypeEnum;
import com.unipay.hosp.client.HospitalFeignClient;
import com.unipay.model.order.OrderInfo;
import com.unipay.model.order.PaymentInfo;
import com.unipay.order.mapper.PaymentInfoMapper;
import com.unipay.order.service.OrderService;
import com.unipay.order.service.PaymentService;
import com.unipay.vo.order.SignInfoVo;
import io.swagger.models.auth.In;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Chenmy
 * @Date 2023/7/18 22:08
 * @Desc TODO
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    /**
     * 保存交易记录
     * @param orderInfo
     * @param paymentType 支付类型（1：微信 2：支付宝）
     */
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer paymentType) {
        // 1、根据orderId、payment_type查询，支付库里是否已经有，这条订单的交易记录
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderInfo.getId());
        queryWrapper.eq("payment_type", paymentType);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0) return;

        // 2、保存，交易记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")+"|"+orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(orderInfo.getAmount());
        baseMapper.insert(paymentInfo);

    }

    // 支付成功：修改订单状态
    @Override
    public void paySuccess(String out_trade_no, Integer paymentType, Map<String, String> resultMap) {
        //（1）根据订单编号，获取支付记录
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("out_trade_no", out_trade_no);
        wrapper.eq("payment_type", paymentType);
        PaymentInfo paymentInfo = baseMapper.selectOne(wrapper);
        //（2）更新：支付状态
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setTradeNo(resultMap.get("transaction_id"));
        paymentInfo.setCallbackContent(resultMap.toString());
        baseMapper.updateById(paymentInfo);
        //（3）根据订单号，获取详细信息
        //（4）更新 ：订单信息
        OrderInfo orderInfo = orderService.getById(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderService.updateById(orderInfo);
        //（5）调用医院接口，更新：订单支付状态
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (null == signInfoVo){
            throw new UnipayException(ResultCodeEnum.PARAM_ERROR);
        }
        HashMap<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = MD5.encrypt(signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        // TODO ----------
        // JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updatePayStatus");
        String originURL = signInfoVo.getApiUrl();
        String magURL = originURL.split(":")[0] + ":" + originURL.split(":")[1] + ":" + "9998";
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, magURL + "/order/updatePayStatus");
        // if (result.getInteger("code") != 200){
        //     throw new UnipayException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        // }
    }

    /*
        TODO 退款
        （1）退款：是根据交易记录发起退款的，所以需要先根据“订单号、支付类型”，获取 “交易记录”
        （2）添加：退款记录
     */
    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("payment_type", paymentType);
        return baseMapper.selectOne(queryWrapper);
    }

}
